#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : Lee

import sys,re
import os
import logging
from SceneCheckTool.checkScript.CheckBase import CheckBase

try:
    import maya.cmds as cmds
    import pymel.core as pm
except:
    pass

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class NSideMeshCheck(CheckBase):
    def __init__(self):
        super(NSideMeshCheck, self).__init__()
        pass

    # 检查模型是否存在6条以上的线连接一个顶点的问题
    def check_vertex_connection(self, mesh):
        problem_vertexes = []
        for index in range(cmds.polyEvaluate(mesh, v=1)):
            vertex_name = "{0}.vtx[{1}]".format(mesh, index)
            if not cmds.polyInfo(vertex_name, ve=1):
                continue
            connect_edges = re.findall(" (\d+ )", cmds.polyInfo(vertex_name, ve=1)[0])
            if len(connect_edges) > 5:
                problem_vertexes.append(index)
        return problem_vertexes

    def vertex_check(self):
        problem_meshes = []
        problem_vertexes = []
        for mesh in cmds.ls(type="mesh"):
            vertex_check_proc = self.check_vertex_connection(mesh)
            if vertex_check_proc:
                problem_meshes.append(mesh)
                for index in vertex_check_proc:
                    name = "{0}.vtx[{1}]".format(mesh, index)
                    if name not in problem_vertexes:
                        problem_vertexes.append(name)
        return problem_vertexes

    def convert_selection_face_to_vertex(self, selected_faces):
        meshes = []
        vertexes = []
        for mesh_face in selected_faces:
            mesh = mesh_face.split(".")[0]
            if mesh not in meshes:
                meshes.append(mesh)
            connect_vertexes = re.findall(" (\d+ )", cmds.polyInfo(mesh_face, fv=1)[0])
            for v in connect_vertexes:
                name = "{0}.vtx[{1}]".format(mesh, v)
                if name not in vertexes:
                    vertexes.append(name)

        cmds.select(cl=1)
        cmds.select(vertexes)
        cmds.hilite(meshes)

    def n_side_polygon_check(self):
        cmds.select(cmds.ls(type="mesh"))
        cmds.polySelectConstraint(m=3, t=8, sz=3)
        cmds.polySelectConstraint(m=0, t=8, sz=0)
        nSideFaces = cmds.ls(selection=True)
        self.convert_selection_face_to_vertex(nSideFaces)
        return nSideFaces

    def check(self):
        result_log = ""
        multi_connect_proc = self.vertex_check()
        if multi_connect_proc:
            result_log += u'<p>Error: 存在六星面模型如下所示 :%s\n</p>' % multi_connect_proc
        else:
            result_log += u'<p>Succeed:六星面检查没有问题</p>\n'

        nSide_polygon_proc = self.n_side_polygon_check()
        if nSide_polygon_proc:
            result_log += u'<p>Error: 存在n边面问题的面如下所示 :%s\n</p>' % nSide_polygon_proc
        else:
            result_log += u'<p>Succeed:n边面检查没有问题\n</p>'

        return result_log

    def fix(self):
        pass

